import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  // 首页
  {
    path: '/home',
    name: 'home',
    component: Home,
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  // 列表页
  {
    path: '/cate',
    name: 'cate',
    component: () => import('@/views/Cate'),
    meta: {
      needLogin: false
    }
  },
  // 购物车页
  {
    path: '/cart',
    name: 'cart',
    component: () => import('@/views/Cart'),
    meta: {
      needLogin: false
    }
  },
  // 用户信息页
  {
    path: '/user',
    name: 'user',
    component: () => import('@/views/User'),
    meta: {
      needLogin: true
    }
  },
  // 登录页
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login'),
    meta: {
      needLogin: false
    }
  },
  // 商品详情路由
  {
    path: '/detail',
    name: 'detail',
    component: () => import('@/views/Detail'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/itemlists/:id',
    name: 'itemlists',
    component: () => import('@/views/ItemLists'),
    meta: {
      needLogin: false
    }
  }
]
const router = new VueRouter({
  // mode: 'history',
  // base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  // 登录鉴权
  if (to.meta.needLogin) {
    // 需要登录
    const token = localStorage.getItem('access_token')
    if (token) {
      next()
    } else {
      // next('login' + to.fullPath) // 动态路由传参
      // params传参
      next({
        name: 'login',
        params: {
          from: to.fullPath
        }
      })
    }
  } else {
    // 不需要登录---可以直接next()放行
    next()
  }
})
export default router
